/*
 * Copyright (c) 2021 Talkweb Co., Ltd.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *    http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
#include <stdio.h>
#include <string.h>
#include <unistd.h>

#include "ohos_init.h"
#include "cmsis_os2.h"

#define MSGQUEUE_COUNT_INDEX_0    0
#define MSGQUEUE_COUNT_INDEX_1    1
#define MSGQUEUE_COUNT_INDEX_2    2
static char *g_cmsisMessageInfo[] = {"msg1", "msg2", "msg3", "msg4", "msg5", "msg6", "msg7", "msg8"};

osMessageQueueId_t MsgQueue;   

void Thread_MsgQueue1(void *arg)
{
	while (1)
	{
		osMessageQueuePut(MsgQueue, g_cmsisMessageInfo[MSGQUEUE_COUNT_INDEX_0], 0U, 0U);
		osThreadYield();
		osDelay(100);
	}
}

void Thread_MsgQueue2(void *arg)
{
	osStatus_t status;

	while (1)
	{
		//wait for message
		status = osMessageQueueGet(MsgQueue, g_cmsisMessageInfo[MSGQUEUE_COUNT_INDEX_0], NULL, 0U);
		if (status == osOK)
		{
			printf("Thread_MsgQueue2 Get msg: %s\n", g_cmsisMessageInfo[MSGQUEUE_COUNT_INDEX_0]);
		}
	}
}

static void Msg_example(void)
{
	MsgQueue = osMessageQueueNew(10, 50, NULL);
	if (MsgQueue == NULL)
	{
		printf("create Message Queue failed!\n");
	}

	osThreadAttr_t attr;

	attr.attr_bits = 0U;
	attr.cb_mem = NULL;
	attr.cb_size = 0U;
	attr.stack_mem = NULL;
	attr.stack_size = 1024 * 10;
	attr.priority = 25;

	attr.name = "Thread_MsgQueue1";
	if (osThreadNew(Thread_MsgQueue1, NULL, &attr) == NULL)
	{
		printf("create Thread_MsgQueue1 failed!\n");
	}

	attr.name = "Thread_MsgQueue2";
	if (osThreadNew(Thread_MsgQueue2, NULL, &attr) == NULL)
	{
		printf("create Thread_MsgQueue2 failed!\n");
	}
}

APP_FEATURE_INIT(Msg_example);
